import { useStore } from "vuex";
import { reactive, Ref, ref, toRaw } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { useForm } from "@ant-design-vue/use";

export default function () {
    const { dispatch } = useStore();
    const router = useRouter();
    const route = useRoute();
    const loading: Ref<boolean> = ref(false);

    const loginForm = reactive({
        username: "admin",
        password: "",
    });

    const rulesRef = reactive({
        username: [
            {
                required: true,
                message: "请输入用户名",
                whitespace: true,
            },
        ],
        password: [
            {
                required: true,
                message: "请输入密码",
                whitespace: true,
            },
        ],
    });
    const { validate, validateInfos } = useForm(loginForm, rulesRef);

    const logout = async () => {
        const res: boolean = await dispatch('user/logout');
        if (res) {
            router.push({ name: "Login" });
        } else {
            message.error("请求出现错误，请稍后再试");
        }
    };


    const login = async () => {
        try {
            const r = await validate();
        } catch (err) {
            return;
        }

        loading.value = true;
        const res = await dispatch('user/login', loginForm);

        if (res) {
            await dispatch('user/authInfo');
            const ref = route.redirectedFrom != undefined ? route.redirectedFrom.fullPath : '/';
            await router.replace(ref);
            message.success("欢迎到来！");
        } else {
            message.error('账号或密码错误！');
        }
        loading.value = false;
    };

    return {
        login,
        logout,
        loginForm,
        loading,
        validateInfos
    };
}
